package com.zjeav.lingjiao.base.utils;

import com.alibaba.fastjson.JSON;
import com.jakewharton.retrofit2.adapter.rxjava2.HttpException;

import java.io.IOException;
import java.net.SocketTimeoutException;

import com.zjeav.lingjiao.base.baseBean.BaseError;

/**
 * Created by zcc on 2017/2/23.
 * 用来显示网络请求的错误信息
 */

public class ErrorUtils {

    public static String showError(Throwable throwable) {
        if (throwable instanceof HttpException) {
            HttpException httpException = (HttpException) throwable;
            BaseError error = null;
            try {
                String errorBody = httpException.response().errorBody().string();
                if (errorBody.contains("DOCTYPE") || errorBody.contains("html")) {
                    return errorBody;
                } else {
                    error = JSON.parseObject(errorBody, BaseError.class);
                    String str_error = error.getMessage();
                    return str_error;
                }
            } catch (IOException e1) {
                e1.printStackTrace();
                return e1.getMessage();
            }
        } else if (throwable instanceof SocketTimeoutException) {
            return "网络不稳定，连接超时，请检查网络设置。";
        } else {
            Exception exception = (Exception) throwable;
            String errorBody = exception.getMessage();
            return errorBody;
        }
    }
    public static String showError(Throwable throwable,String message) {
        if (throwable!=null){
            if (throwable instanceof HttpException) {
                HttpException httpException = (HttpException) throwable;
                BaseError error = null;
                try {
                    String errorBody = httpException.response().errorBody().string();
                    if (errorBody.contains("DOCTYPE") || errorBody.contains("html")) {
                        return errorBody;
                    } else {
                        error = JSON.parseObject(errorBody, BaseError.class);
                        String str_error = error.getMessage();
                        return str_error;
                    }
                } catch (IOException e1) {
                    e1.printStackTrace();
                    return e1.getMessage();
                }
            } else if (throwable instanceof SocketTimeoutException) {
                return "网络不稳定，连接超时，请检查网络设置。";
            } else {
                Exception exception = (Exception) throwable;
                String errorBody = exception.getMessage();
                return errorBody;
            }
        }else {
            return message;
        }

    }
}
